package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
//        List<String> jsonList =  stringRedisTemplate.opsForList().range("cache:shop:type", 0, -1);
//        if (jsonList != null && jsonList.size() > 0) {
//            List<ShopType> tpList = new ArrayList<>();
//            for (String json : jsonList) {
//                ShopType shopType = JSONUtil.toBean(json, ShopType.class);
//                tpList.add(shopType);
//            }
//            return Result.ok(tpList);
//        }
        String value = stringRedisTemplate.opsForValue().get("cache:shop:type");
        if (StrUtil.isNotBlank( value)) {
            List<ShopType> typeList = JSONUtil.toList(value, ShopType.class);
            return Result.ok(typeList);
        }
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
//        List<String> cacheList = new ArrayList<>();
//        for (ShopType shopType : typeList) {
//            cacheList.add(JSONUtil.toJsonStr(shopType));
//        }
        stringRedisTemplate.opsForValue().set("cache:shop:type", JSONUtil.toJsonStr(typeList));

// 4. 存入 Redis（使用 leftPushAll 批量插入）
//        stringRedisTemplate.opsForList().leftPushAll("cache:shop:type", cacheList);

// 5. 返回数据库查询结果

        return Result.ok(typeList);
    }
}
